#include "ui.hpp"

#include <opencv2/highgui/highgui.hpp>

#include <cstdio>
#include <algorithm>


void get_calibration_rects(cv::Mat& img, cv::Rect& left, cv::Rect& right)
{
  int img_w = img.size().width - 1;
  int img_h = img.size().height - 1;

  int rect_w = img_w * RECT_WIDTH;
  int rect_h = img_h * RECT_HEIGHT;

  int center_a_x = img_w * RECT_HOR_OFFSET;
  int center_a_y = img_h - (img_h * RECT_VER_OFFSET);

  int center_b_x = img_w - center_a_x;
  int center_b_y = center_a_y;

  center_a_x += RECT_X_PADDING * img_w;
  center_b_x += RECT_X_PADDING * img_w;
  center_a_y += RECT_Y_PADDING * img_h;
  center_b_y += RECT_Y_PADDING * img_h;

  cv::Point2i a_tl(center_a_x - rect_w/2, center_a_y - rect_h/2);
  cv::Point2i a_br(center_a_x + rect_w/2, center_a_y + rect_h/2);

  cv::Point2i b_tl(center_b_x - rect_w/2, center_b_y - rect_h/2);
  cv::Point2i b_br(center_b_x + rect_w/2, center_b_y + rect_h/2);

  left = cv::Rect(a_tl, a_br);
  right = cv::Rect(b_tl, b_br);
}


void draw_calibration_rects(cv::Mat& img, cv::timer calibration_timer)
{
  cv::Rect left, right;
  get_calibration_rects(img, left, right);

  double time = cv::seconds_spent(calibration_timer) / CALIBRATION_TIMEOUT;
  time = std::min(time, 1.0);

  // fade from green to red
  cv::Scalar_<uchar> color(0, 255*(1-time), 255*time);

  cv::rectangle(img, left, color, 2);
  cv::rectangle(img, right, color, 2);
}


void draw_ui(cv::Mat& img, cv::Point2i& pt_a, cv::Point2i& pt_b, HandState& hand_st)
{
  HandState::Distance distance = hand_st.distance;
  HandState::Direction direction = hand_st.direction;

  cv::Scalar line_color;

  if (distance == HandState::CLOSE)
    line_color = cv::RED;
  else if (distance == HandState::FAR)
    line_color = cv::GREEN;
  else
    line_color = cv::BLUE;

  cv::line(img, pt_a, pt_b, line_color, 2, CV_AA);

  cv::Scalar left_color = cv::WHITE, right_color = cv::WHITE;

  if (direction == HandState::LEFT)
    left_color = cv::GREEN;
  else if (direction == HandState::RIGHT)
    right_color = cv::GREEN;

  cv::circle(img, pt_a, (direction == HandState::LEFT ? 5 : 3), left_color, -1, CV_AA);
  cv::circle(img, pt_b, (direction == HandState::RIGHT ? 5 : 3), right_color, -1, CV_AA);
}
